package it.antonio.ilpizze.swing.util;


import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public abstract class SimpleTableModel<T> extends AbstractTableModel {

	private static final long serialVersionUID = 1L;
	
	protected List<T> modelData;
	protected List<String> columnNames;
	
	protected SimpleTableModel(List<T> modelData, List<String> columnNames) {
		this.modelData = modelData;
		this.columnNames = columnNames;
		fireTableStructureChanged();
		
	}
	
	public abstract Object[] toRow(T obj);
	
	@Override
	public int getColumnCount() {
		return columnNames.size();
	}
	
	public String getColumnName(int column) {
		Object columnName = null;

		if (column < columnNames.size()) {
			columnName = columnNames.get( column );
		}

		return (columnName == null) ? super.getColumnName( column ) : columnName.toString();
	}
	
	@Override
	public int getRowCount() {
		return modelData.size();
	}

	@Override
	public Object getValueAt(int row, int column) {
		Object[] rowData = toRow(modelData.get(row)); 
		return rowData[column];
	}

	public void insertRow(int row, T rowData) {
		modelData.add(row, rowData);
		fireTableRowsInserted(row, row);
	}
	
	public void addRow(T rowData) {
		insertRow(getRowCount(), rowData);
	}

	public T getRow(int row) {
		return modelData.get( row );
	}

	public List<T> getRowsAsList(int... rows) {
		List<T> rowData = new ArrayList<T>(rows.length);

		for (int i = 0; i < rows.length; i++) {
			rowData.add( getRow(rows[i]) );
		}

		return rowData;
	}
	
	public void insertRows(int row, List<T> rowList) {
		modelData.addAll(row, rowList);
		fireTableRowsInserted(row, row + rowList.size() - 1);
	}
	
	public void replaceRow(int row, T rowData) {
		modelData.set(row, rowData);
		fireTableRowsUpdated(row, row);
	}
	
	public void removeRow(int row) {
		modelData.remove(row);
		fireTableRowsDeleted(row, row);
	}

	public void setModelData(List<T> modelData) {
		this.modelData = modelData;
		fireTableDataChanged();
	}

	
}
